package j20251025;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Demo2 {
    public static void main(String[] args) {
        // 1. 创建固定大小的线程池
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);

        // 2. 创建单线程的线程池
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();

        // 3. 创建可缓存的线程池
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

        // 4. 创建定时任务线程池
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2);

        System.out.println("=== 固定大小线程池示例 ===");
        // 提交5个任务给固定大小的线程池
        for (int i = 1; i <= 5; i++) {
            final int taskId = i;
            fixedThreadPool.execute(() -> {
                System.out.println("固定线程池任务 " + taskId + " 运行在: " + Thread.currentThread().getName());
            });
        }

        System.out.println("\n=== 单线程池示例 ===");
        // 提交3个任务给单线程池
        for (int i = 1; i <= 3; i++) {
            final int taskId = i;
            singleThreadExecutor.execute(() -> {
                System.out.println("单线程池任务 " + taskId + " 运行在: " + Thread.currentThread().getName());
            });
        }

        System.out.println("\n=== 可缓存线程池示例 ===");
        // 提交5个任务给可缓存线程池
        for (int i = 1; i <= 5; i++) {
            final int taskId = i;
            cachedThreadPool.execute(() -> {
                System.out.println("缓存线程池任务 " + taskId + " 运行在: " + Thread.currentThread().getName());
            });
        }

        System.out.println("\n=== 定时任务线程池示例 ===");
        // 延迟2秒执行一次
        scheduledThreadPool.schedule(() -> {
            System.out.println("延迟任务执行于: " + Thread.currentThread().getName());
        }, 2, TimeUnit.SECONDS);

        // 关闭线程池
        fixedThreadPool.shutdown();
        singleThreadExecutor.shutdown();
        cachedThreadPool.shutdown();
        scheduledThreadPool.shutdown();

        try {
            // 等待所有线程池终止
            fixedThreadPool.awaitTermination(1, TimeUnit.SECONDS);
            singleThreadExecutor.awaitTermination(1, TimeUnit.SECONDS);
            cachedThreadPool.awaitTermination(1, TimeUnit.SECONDS);
            scheduledThreadPool.awaitTermination(3, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("\n所有任务执行完成！");
    }
}
